﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace XamlInspector.Foundation
{
    public class MergeableObservableCollection<T> : ObservableCollection<T>
    {
        public MergeableObservableCollection(IEnumerable<T> items = null)
        {
            if (items != null)
            {
                items.ForEach(Add);
            }
        }

        public void AddRange(IEnumerable<T> items)
        {
            CheckReentrancy();
            items.ForEach(Add);
        }

        public void InsertRange(IEnumerable<T> items)
        {
            CheckReentrancy();
            foreach (var item in items)
            {
                Add(item);
            }
        }

        public void Merge(IEnumerable<T> currentItems)
        {
            CheckReentrancy();

            if (currentItems == null)
            {
                Clear();
            }
            else
            {
                var currentList = currentItems.ToList();

                // Remove old items
                var itemsToRemove = this.Except(currentList).ToList();
                itemsToRemove.ForEach(i => Remove(i));

                // Add new items
                var itemsToAdd = currentList.Except(this).ToList();
                itemsToAdd.ForEach(Add);
            }
        }
    }
}
